package cn.topcode.unicorn.utils;

import com.alibaba.fastjson.annotation.JSONField;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import java.lang.reflect.Field;
import java.util.*;

/**
 * Created by Unicorn on 2017/12/31.
 */
public class SignUtil {

    /**
     * 计算签名
     * @param obj
     * @return
     */
    public static String sortField(Object obj, String... ignoreProperty) {
        List<String> ignoreProps = Arrays.asList(ignoreProperty);

        //  1.取出非空参数值的参数和取值
        Field[] fields = obj.getClass().getDeclaredFields();

        List<String> names = new ArrayList<>();
        Map<String, String> map = new HashMap<>();

        for(Field field : fields) {
            if(ignoreProps.contains(field.getName())) {
                continue;
            }
            try {
                field.setAccessible(true);
                Object value = field.get(obj);
                if(value != null) {
                    String fieldName = null;

                    XStreamAlias xStreamAlias = field.getAnnotation(XStreamAlias.class);
                    JSONField jsonField = field.getAnnotation(JSONField.class);
                    if(xStreamAlias != null) {
                        fieldName = xStreamAlias.value();
                    }else if(jsonField != null) {
                        fieldName = jsonField.name();
                    }else {
                        fieldName = field.getName();
                    }

                    names.add(fieldName);
                    map.put(fieldName, value.toString());
                }
            } catch (Exception e) {}
        }

        //  2.按照ascii排序
        Collections.sort(names, new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });

        //  3.按照 name1=value&name2=value 形式拼接
        StringBuilder sb = new StringBuilder();
        for(int i = 0 ; i < names.size() ; i ++ ) {
            String name = names.get(i);
            if(i != 0) {
                sb.append("&");
            }
            sb.append(name);
            sb.append("=");
            sb.append(map.get(name));
        }
        return sb.toString();
    }
}
